package com.example.rabbitmq.config;

import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Objects;

@Configuration
public class RabbitTemplateConfig {

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);

        // 设置确认回调
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                String correlationId = Objects.isNull(correlationData) ? "correlationId未知" : correlationData.getId();
                System.out.println("消息发送成功，correlationId: " + correlationId);
            } else {
                System.out.println("消息发送失败，原因: " + cause);
                // 可以在这里进行重试或记录日志
            }
        });

        // 设置返回回调
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            System.out.println("消息投递到队列失败！");
            System.out.println("消息: " + new String(message.getBody()));
            System.out.println("响应码: " + replyCode);
            System.out.println("响应信息: " + replyText);
            System.out.println("交换机: " + exchange);
            System.out.println("路由键: " + routingKey);
        });


        return rabbitTemplate;
    }
}
